//
//  ProductDetail.m
//  mbstore
//
//  Created by Juvid on 14-4-15.
//  Copyright (c) 2014年 huangyi. All rights reserved.
//

#import "ProductDetail.h"
#import "StrikeThroughLabel.h"
#import "ProductUIV.h"
#import "DefultCor.h"
#import "UIImageView+WebCache.h"
#import "SearchStock.h"
@implementation ProductDetail

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        [self addSubview:self.tableView];
        self.tableView.delegate=self;
        self.tableView.dataSource=self;
        self.tableView.separatorInset=UIEdgeInsetsMake(0, 0, 0, 0);
        self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        self.tableView.showsHorizontalScrollIndicator=NO;
        self.tableView.showsVerticalScrollIndicator=NO;
        self.backgroundColor=[UIColor whiteColor];
        self.tableView.bounces=NO;
        self.tableView.rowHeight=90;
        [self.layer setBorderWidth:2];
        [self.layer setBorderColor: TABLEBOR.CGColor];
        self.mlIsShow=[NSMutableArray arrayWithObjects:[NSNumber numberWithBool:YES],[NSNumber numberWithBool:YES],[NSNumber numberWithBool:YES],nil];
        self.mlRowNum=[NSMutableArray arrayWithObjects:@"1",@"4",@"1",nil];
        sizeFram=CGRectMake(-(self.frame.size.width-43), 105, self.frame.size.width*2, 9);
        mlDicStock=[NSMutableDictionary dictionary];
        //        mlSecRow=[[NSMutableArray alloc]initWithObjects:@"1",@"4",@"1" ,nil];
        [self.tableView reloadData];
       
        //        UIView *vieHead=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 300, 45)];
        //        vieHead.backgroundColor=[UIColor redColor];
        //        [self addSubview:vieHead];
        // Initialization code
        
        
#pragma mark 初始化商品库存查询server
        self.commoditiesc = [[CommoditiesController alloc] init];
    }
    return self;
}
- (void)setViewHight:(void (^) (CGFloat hight))vieHight{
    SetVieHight=[vieHight copy];
}
-(void)GetStock:(NSString *)skuId{
    _servers=[SearchStock GetStocks:skuId];
    _servers.delegate = self;
    
    
//    NSArray *colors=_dicDetail[@"colors"];
//    NSArray *size=[colors objectAtIndex:currentColor][@"sizes"];
//    isFinishLoad=NO;
//    NSLog(@"%d   %d",size.count,totla);
//    if (totla<size.count&&!isFinishLoad) {
//          NSDictionary *everySize=[size objectAtIndex:totla];
//        [self.commoditiesc GetStockJson:skuId
//                                Success:^(NSDictionary *dicReceiveData) {
//                                    isFinishLoad=YES;
//                                    [self GetStock:everySize[@"sku"]];
//                                    if (mlAllStock==nil) {
//                                        mlAllStock=[NSMutableArray array];
//                                    }else{
//                                        NSMutableDictionary *dic;
//                                        if (mlAllStock.count==0) {
//                                            dic=[NSMutableDictionary dictionary];
////                                           [ mlAllStock
//                                        }
//                                        else{
//                                            dic=[mlAllStock objectAtIndex:currentColor];
//                                        }
//                                        [dic setObject:dicReceiveData[@"HandStock"] forKey:everySize[@"sku"]];
//                                        [mlAllStock setObject:dic atIndexedSubscript:currentColor];
//                                    }
//            
//        }
//                                Failure:^(NSError *error) {
//            isFinishLoad=YES;
//            
//        }];
//      totla++;
//    }
   }


-(void)receiveData:(NSDictionary *)dic WithPath:(NSString *)path
{
    
}
-(void)FailureData:(NSString *)path WithError:(NSError *)error{
    [mlDicStock setObject:@"22" forKey:path];
    [self.tableView reloadData];
    NSLog(@"%@",path);
}

-(void)setDicDetail:(NSDictionary *)dicDetail{
    _dicDetail=dicDetail;
    NSArray *colors=_dicDetail[@"colors"];
//    mlStock=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"colors",@"colors", nil];
    NSArray *size=[colors objectAtIndex:0][@"sizes"];
    [self.mlRowNum setObject:[NSNumber numberWithInt:size.count+2] atIndexedSubscript:1];
//    NSDictionary *everySize=[size objectAtIndex:0];
//    [self GetStock:everySize[@"sku"]];
    [self ShowProductColor];
    [self.tableView reloadData];
}
-(void)ShowProductColor{
    self.colorScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(31, 15, self.frame.size.width-62, 90)];
    self.colorScrollView.delegate=self;
    self.colorScrollView.showsVerticalScrollIndicator=NO;
    NSArray *colors=_dicDetail[@"colors"];
    UIButton *cb=nil;
    for (int i=0; i<colors.count; i++) {
        UIButton *button=[self colorButton:i];
        button.tag=1556+i;
        button.frame=CGRectOffset(button.bounds, ((CGRectGetWidth(button.bounds))+8)*i, 5);
        [self.colorScrollView addSubview:button];
        self.colorScrollView.contentSize=CGSizeMake(CGRectGetMaxX(button.frame), CGRectGetHeight(button.frame));
        if (i==0) cb=button;
    }
//

}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    // Return the number of sections.
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    //    if (dicGetDetail.count>0) {
    if (_dicDetail) {
        if ([[self.mlIsShow objectAtIndex:section]boolValue]) {
            return [[self.mlRowNum objectAtIndex:section] intValue];
        }
    }
    return 0;
    
    //    }
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier=@"pdt";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.clipsToBounds=YES;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
    }
    else{
        while ([cell.contentView.subviews lastObject] != nil)
        {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
        
    }

    if (indexPath.section==0) {
        //        基本信息
        if (indexPath.row==0) {
            UILabel *labName=[[UILabel alloc]initWithFrame:CGRectMake(10, 10, self.frame.size.width, 20)];
            //            labName.numberOfLines=0;
            labName.font=[UIFont systemFontOfSize:14];
            [cell.contentView addSubview:labName];
            
            UILabel *labNum=[[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(labName.bounds)+12, self.frame.size.width, 20)];
            
            labNum.font=[UIFont systemFontOfSize:14];
            [cell.contentView addSubview:labNum];
            
            UILabel *labMoney=[[UILabel alloc]initWithFrame:CGRectMake(10, 55, 60, 20)];
            StrikeThroughLabel *strikeLab=[[StrikeThroughLabel alloc]initWithFrame:CGRectMake(labMoney.frame.size.width+5, 55, 60, 20)];
            
            if (_dicDetail) {
                labName.text=[NSString stringWithFormat:@"%@\n",_dicDetail[@"goodsName"]];
                labNum.text=[NSString stringWithFormat:@"商品编号：%@",_dicDetail[@"colorSn"]];
//                labMoney.text=[NSString stringWithFormat:@"¥%@",_dicDetail[@"price"]];
#pragma mark 添加price
#warning 套装事报错
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:@"" forKey:kUserID];
                [self.commoditiesc ScanBarCodeIntoBillEntity:_dicDetail[@"colorSn"] Qty:@"1" ContainerID:@"" IsJudgePrice:@"true" StartNum:1 EndNum:1 Success:^(NSDictionary *dicReceiveData) {
                    
                    NSMutableArray * entityArray = [dicReceiveData objectForKey:@"Message"];
                    EPOSDetailEntity * entity = [entityArray objectAtIndex:0];
                    NSLog(@"+%@",entity.SalesValue);
//                    [suit setValue:entity.SalesValue forKey:@"price"];
                    labMoney.text=[NSString stringWithFormat:@"¥%@",entity.SalesValue];
                    
                    
                } Failure:^(NSError *error) {
                    [SVProgressHUD showErrorWithStatus:@"查询价格出错！"];
                }];

                strikeLab.text=[NSString stringWithFormat:@"¥%@",_dicDetail[@"marketPrice"]];;
            }
            strikeLab.strikeThroughEnabled=YES;
            strikeLab.textColor=[UIColor lightGrayColor];
            labMoney.textColor=[UIColor redColor];
            [cell.contentView addSubview:labMoney];
            [cell.contentView addSubview:strikeLab];
        }
        
    }
    
    
    
    //    当前颜色库存
    else if(indexPath.section==1){
        if (indexPath.row==0) {
            [cell.contentView addSubview:self.colorScrollView];
            //            左右按钮
            for (int i=0; i<2; i++) {
                UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(0+i*(CGRectGetMaxX(self.colorScrollView.frame)-2), 35, 30, 30)];
                //                btn.backgroundColor=[UIColor blackColor];
                if (i==0) {
                    [btn setImage:[UIImage imageNamed:@"colorLeft"] forState:UIControlStateNormal];
                    //                    btn.enabled=NO;
                }
                else  [btn setImage:[UIImage imageNamed:@"colorRight"] forState:UIControlStateNormal];
                [btn addTarget:self action:@selector(NextImg:) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:btn];
            }
//            红色分割线
            UIImageView *imgLine=[[UIImageView alloc]initWithFrame:sizeFram];

//            imgLine.frame=sizeFram;
            imgLine.tag=2012;
            imgLine.image=[UIImage imageNamed:@"colorSizeLine"];
            [cell.contentView addSubview:imgLine];
            
        }
        else{
            UILabel *labSize=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 90, 44)];
            UILabel *labStock=[[UILabel alloc]initWithFrame:CGRectMake(90, 0, 60, 44)];
           
            
            //            第一行
            if (indexPath.row==1) {
                UILabel *labCart=[[UILabel alloc]initWithFrame:CGRectMake(150, 0, 100, 44)];
                labSize.text=@"尺寸" ;
                labStock.text=@"库存";
                labCart.text=@"加入购物车";
                labCart.font=[UIFont systemFontOfSize:15];
                labCart.textAlignment=NSTextAlignmentCenter;
                [cell.contentView addSubview:labCart];
            }
            //            其他行
            else {
                NSArray *colors=_dicDetail[@"colors"];
                NSArray *size=[colors objectAtIndex:currentColor][@"sizes"];
                NSDictionary *everySize=[size objectAtIndex:indexPath.row-2];
                UIButton *btnCart=[[UIButton alloc]initWithFrame:CGRectMake(165, 10, 70, 24)];
                [btnCart setTitle:@"加入" forState:UIControlStateNormal];
                [btnCart setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [btnCart addTarget:self action:@selector(AddCart:) forControlEvents:UIControlEventTouchUpInside];
                btnCart.titleLabel.font=[UIFont systemFontOfSize:14];
                btnCart.backgroundColor=ORANGE;
                [btnCart.layer setCornerRadius:12];
                [btnCart setClipsToBounds:YES];
                [cell.contentView addSubview:btnCart];
                labSize.text=everySize[@"sizeName"];
                 labStock.text=@"...";
//                NSMutableDictionary *mlDic=[mlAllStock objectAtIndex:indexPath.row-2];
                if ([mlDicStock objectForKey:everySize[@"sku"]]) {
                    labStock.text=[mlDicStock objectForKey:everySize[@"sku"]];
                   
                }
                else{
                    [self GetStock:everySize[@"sku"]];
                }
               
                
            }
            
            labSize.font=[UIFont systemFontOfSize:15];
            labSize.textAlignment=NSTextAlignmentCenter;
            [cell.contentView addSubview:labSize];
            labStock.font=[UIFont systemFontOfSize:15];
            labStock.textAlignment=NSTextAlignmentCenter;
            [cell.contentView addSubview:labStock];
            UIView *labLine=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetHeight([self.tableView rectForRowAtIndexPath:indexPath])-1, CGRectGetWidth([self.tableView rectForRowAtIndexPath:indexPath]), 0.5)];
            labLine.backgroundColor=LINECOR;
            [cell.contentView addSubview:labLine];
        }
    }
    
    
    
    //    卖点
    else if (indexPath.section==2){
        UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(10, 15, CGRectGetWidth(self.frame)-20, CGRectGetHeight([self.tableView rectForRowAtIndexPath:indexPath])-30)];
        lab.text=@"大家来看感觉放假了凯撒几个考虑到附近的萨拉克国际法的离开过家风刀霜剑阿拉贡解放东路开关机多乐士家阿哥了房间号";
        lab.numberOfLines=0;
        lab.font=[UIFont systemFontOfSize:15];
        [cell.contentView addSubview:lab];
        
    }
    //    cell.textLabel.text=@"fslkahgl";
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0)return 90;
    else if(indexPath.section==1){
        if (indexPath.row==0)  return 120;
        else return 44;
    }
    return 90;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 38;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *vieResult=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, CGRectGetHeight([self.tableView rectForHeaderInSection:section]))];
    
    //    [vieResult.layer setBorderWidth:1];
    //    [vieResult.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    
    UILabel *result=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, vieResult.frame.size.height)];
    result.backgroundColor=[UIColor colorWithRed:229.0/255.0 green:229.0/255.0 blue:229.0/255.0 alpha:1];
    
    result.text=@"  男 | 长袖衬衫";
    [vieResult addSubview:result];
    UIButton *btnSelect;
    if (section!=0) {
        btnSelect=[[UIButton alloc]initWithFrame:CGRectMake(self.frame.size.width-40, 4, 30, 30)];
        result.font=[UIFont systemFontOfSize:15];
        [btnSelect setImage:[UIImage imageNamed:@"colorDown"] forState:UIControlStateNormal];
        [btnSelect addTarget:self action:@selector(HideRow:) forControlEvents:UIControlEventTouchUpInside];
        btnSelect.tag=10001+section;
        if (section==1) {
            result.text=@"  当前颜色库存";
        }
        else {
            result.text=@"  卖点";
        }
        [vieResult addSubview:btnSelect];
        
    }
    else{
        if (!self.isSuit) {
            btnSelect=[UIButton buttonWithType:UIButtonTypeContactAdd];
            btnSelect.frame=CGRectMake(self.frame.size.width-40, 0, 35, vieResult.frame.size.height);
            [btnSelect addTarget:self action:@selector(ShowTree:) forControlEvents:UIControlEventTouchUpInside];
            btnSelect.tintColor=[UIColor colorWithRed:127.0/255.0 green:127.0/255.0 blue:127.0/255.0 alpha:1];
            [vieResult addSubview:btnSelect];
            
        }
    }

    return vieResult;
}
-(void)NextImg:(UIButton *)sender{
    for (UIView *subView in sender.superview.subviews) {
        if ([subView isKindOfClass:[UIButton class]]) {
            UIButton *btn=(UIButton *)subView;
            btn.enabled=NO;
        }
    }
    sender.enabled=YES;
    
}
//折叠效果
-(void)HideRow:(UIButton *)sender{
    
    [self.tableView beginUpdates];
    int section=sender.tag-10001;
    BOOL isOpen=NO;
    NSMutableArray* rowToInsert = [[NSMutableArray alloc] init];
	for (int i=0; i<[[self.mlRowNum objectAtIndex:section]intValue]; i++) {
        NSIndexPath* indexPathToInsert = [NSIndexPath indexPathForRow:i inSection:section];
        [rowToInsert addObject:indexPathToInsert];
    }
    if ([[self.mlIsShow objectAtIndex:section]boolValue]) {
        [self.mlIsShow setObject:[NSNumber numberWithBool:NO] atIndexedSubscript:section];
        [sender setImage:[UIImage imageNamed:@"colorUp"] forState:UIControlStateNormal];
        [self.tableView deleteRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationTop];
    }
    else{
        
        [self.mlIsShow setObject:[NSNumber numberWithBool:YES] atIndexedSubscript:section];
        [sender setImage:[UIImage imageNamed:@"colorDown"] forState:UIControlStateNormal];
        
        [self.tableView insertRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationBottom];
        
        isOpen=YES;
        
        
    }
    [self.tableView endUpdates];
    if (isOpen) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
    
    
    
    //    [self performSelector:@selector(UpdateVie) withObject:nil afterDelay:.5];
    
}
//显示筛选分类
-(void)ShowTree:(UIButton *)sender{
    ProductUIV *productVie=(ProductUIV *)self.superview;
    [productVie setStrSuit:self.strSuit];
    [self.itemdelegate ShowTree:productVie];
     [[NSNotificationCenter defaultCenter] postNotificationName:ChangSelcetType object:self.strSuit];
}
//单品各个颜色
-(UIButton*)colorButton:(int)indexs{
    NSArray *colors=_dicDetail[@"colors"];
  NSDictionary  *sku=[colors objectAtIndex:indexs];
    UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:@selector(onColorClick:) forControlEvents:UIControlEventTouchUpInside];
    button.frame=CGRectMake(0, 0, 60, 85);
    [button setTitle:sku[@"colorName"] forState:UIControlStateNormal];
    [button setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    button.titleLabel.font=[UIFont systemFontOfSize:12];
    UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    imageView.tag=1001;
    [button addSubview:imageView];
    NSString *image=sku[@"mainPhoto"];
    image = [image stringByDeletingPathExtension];
    image = [NSString stringWithFormat:@"%@--w_40_h_40.jpg",image];
    NSString *imageURL=[AppUI getImageURL:image];
    [imageView setImageWithURL:[NSURL URLWithString:imageURL]];
    if (currentColor==indexs) {
        imageView.layer.borderColor=[[UIColor redColor] CGColor];
        imageView.layer.borderWidth=1;
    }
    else{
        imageView.layer.borderColor=[[UIColor grayColor] CGColor];
        imageView.layer.borderWidth=1;
    }
    //    [imageView setImageURL:imageURL];
    return button;
}
-(void)onColorClick:(UIButton *)sender{
    for (id view in self.colorScrollView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *button=view;
            if (button==sender) {
                UIView *view=[button viewWithTag:1001];
                view.layer.borderColor=[[UIColor redColor] CGColor];
                view.layer.borderWidth=1;
                UIImageView *imgLine=(UIImageView *)[self viewWithTag:2012];
                currentColor=sender.tag-1556;
               
                //                移动红色位置
                sizeFram=CGRectOffset(imgLine.bounds, (CGRectGetMidX(sender.frame)-self.colorScrollView.contentOffset.x-self.colorScrollView.frame.size.width-50), imgLine.frame.origin.y);
//重新加载库存尺寸
                NSArray *colors=_dicDetail[@"colors"];
                NSArray *size=[colors objectAtIndex:currentColor][@"sizes"];
                [self.mlRowNum setObject:[NSNumber numberWithInt:size.count+2] atIndexedSubscript:1];
                 [self.tableView reloadData];
                
                //                self.sku[@"color_name"]=button.payloadObject[@"color_name"];
                //                NSString *imageName =button.payloadObject[@"main_photo"];
                //                imageName = [imageName stringByDeletingPathExtension];
                //                imageName = [NSString stringWithFormat:@"%@--w_320_h_320.jpg",imageName];
                //                NSString *imageURL=[AppUI getImageURL:imageName];
                //                self.itemImage.image = nil;
                //                [self.itemImage setImageURL:imageURL];
            }else{
                UIView *view=[button viewWithTag:1001];
                view.layer.borderColor=[[UIColor grayColor] CGColor];
                view.layer.borderWidth=1;
            }
        }
    }
    //    [self checkStock];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if([scrollView isEqual:self.colorScrollView]){
        
        if (scrollView.contentOffset.x>=scrollView.contentSize.width-scrollView.frame.size.width) {
            NSLog(@"右");
        }
        else if(scrollView.contentOffset.x<=0){
            NSLog(@"左");
        }
        
    }
}
-(void)UpdateVie{
    NSLog(@"%f",self.tableView.contentSize.height);
    SetVieHight(self.tableView.contentSize.height);
}
-(void)AddCart:(UIButton *)sender{
    
}
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */

@end
